//    Copyright (C) Kherty.  All rights reserved.
using System;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Windows.Data;
using System.Resources;
using System.Reflection;

namespace OpenLS.Drawing.UI
{
    internal class EnumToNameConverter : IValueConverter
    {
        #region IValueConverter Members

        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            try
            {
                if (value == null)
                    return "";
                var type = value.GetType();
                string s = string.Format("{0}_{1}", type.Name, value);
                string str = getAssemblyName(type.Assembly);
                if (!str.EndsWith(".UI"))
                    str = str + ".UI";
                var a = Assembly.Load(str);
                string s2 = getAssemblyName(a);
                var man = new ResourceManager(s2 + ".EnumTable", a);
                //string result = EnumTable.ResourceManager.GetString(s);
                var result = man.GetString(s);
#if DEBUG
                // if (result == null)
                    //Contract.Assert(false);
#endif
                // Contract.Assert(result != null, s);
                return result;
            }
            catch (Exception e)
            {
                throw;
            }
        }

        static string getAssemblyName (Assembly assembly)
        {
            string result = assembly.FullName;
            int i = result.IndexOf(',');
            if (i > 0)
                result = result.Substring(0, i);
            return result;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotSupportedException();
        }

        #endregion
    }
}
